#!/bin/sh

TARGETS="*.c *.h *.cpp *.hpp *.txt *.dat"

echo "BOM tool"

if [ -z $1 ] ; then
	echo -e "usage:\n    -r    remove BOM\n    -a    add BOM"
	exit
fi

BOM=`echo -n -e "\xEF\xBB\xBF"`

for i in $TARGETS
do
#	echo "($i)"
	LIST=`find . -name "$i" -print`
	
	for src in $LIST
	do
		
		HEAD=`head -c 3 $src`
		if [ "$HEAD" = $BOM ] ; then
			#BOMがついている
			
			if [ $1 = "-a" ] ; then
				echo "$src has already had a BOM."
			fi
			
			if [ $1 = "-r" ] ; then
				mv $src $src.remove_bom_temp
				dd if=$src.remove_bom_temp of=$src ibs=1 obs=1 skip=3 seek=0 &>/dev/null
				rm $src.remove_bom_temp
				echo "$src's BOM was removed."
			fi
			
		else
			#BOMがついていない
			
			if [ $1 = "-a" ] ; then
				mv $src $src.add_bom_temp
				echo -n -e "\xEF\xBB\xBF" > $src
				cat $src.add_bom_temp >> $src
				rm $src.add_bom_temp
				echo "BOM was added to $src."
			fi
			
			if [ $1 = "-r" ] ; then
				echo "$src doesn't have a BOM."
			fi
			
		fi
		
	done
done

echo "<done>"

